<?php
namespace app\common\controller;

use app\BaseController;
use app\socket\Server;
use think\App;
use think\facade\View;
use think\swoole\Websocket;

class Wx extends BaseController
{

    protected string $appId;
    protected string $appSecret;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->appId = env('GZH.APPID');
        $this->appSecret = env('GZH.APP_SECRET');
    }

    public function login(): string
    {
        $token = $this->request->param('token');
        $url = get_http_url().'/common/wx/getCode?token='.$token;
        View::assign(['url' => $url]);
        return View::fetch('login');
    }

    public function getCode(): void
    {
        $token = $this->request->param('token');
        $redirect_uri = get_http_url().'/common/wx/getOpenid?token='.$token;
        $redirect_uri = urlencode($redirect_uri);
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appId.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state='.$token.'#wechat_redirect';
        header('Location: '.$url);
    }

    public function getOpenid(Websocket $websocket): bool|string
    {
        $code = $this->request->param('code');
        $token = $this->request->param('state');
        $data = get_curl('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appId.'&secret='.$this->appSecret.'&code='.$code.'&grant_type=authorization_code');
        $data = json_decode($data,true);
        if (!$data['openid']) return error('系统错误！');
        cache($token,$data['openid'],30);
        //推送socket消息
        $socketServer = new Server();
        $fd = $socketServer->uidGetFd($token);
        $socketServer->push($fd,json_encode([
            'type' => 'wxLogin',
            'type_name' => '二维码登录回调'
        ]),$websocket);
        return success([],'登录成功！');
    }
}